package com.roocon.design_pattern.chapter04_future_design;

import java.util.function.Consumer;

public class FutureService {

  /**
   * FutureTask 把事情做完后把返回结果放到Future里面，
   * 当外部调用get接口的时候返回
   * @param task
   * @param <T>
   * @return
   */
  public <T> Future<T> submit(final FutureTask<T> task){
    AsynFuture<T> asynFuture = new AsynFuture<>();
    new Thread(()->{
      T result = task.call();
      asynFuture.done(result);
    }).start();
    return asynFuture;
  }

  /**
   *
   * @param task
   * @param consumer 增加callback 回调
   * @return
   */
  public <T> Future<T> submit(final FutureTask<T> task, final Consumer<T> consumer){
    AsynFuture<T> asynFuture = new AsynFuture<>();
    new Thread(()->{
      T result = task.call();
      asynFuture.done(result);
      consumer.accept(result);
    }).start();
    return asynFuture;
  }
}
